package com.zgh.zhongcan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgh.zhongcan.common.R;
import com.zgh.zhongcan.entity.Employee;

import com.zgh.zhongcan.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author 时侍
 * @version 1.0
 **/
@Slf4j
@RestController//RestController的作用相当于Controller加ResponseBody,且支持Restful风格的数据提交方式
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //1将提交来的密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2查询数据库，对用户名和密码进行判断
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //当表结构发生改变时，如@TableField(value = "user_name") 更改为 @TableField(value = "name")只要类的成员变量别名不变，就不会影响到程序结果的获取
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3若没查到则返回登录失败
        if (emp==null){
            return R.error("无此用户");
        }

        //4比对密码（转换为明文），不一致则返回失败
        if (!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }

        //5查看员工状态是否可用
        if (emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6登录成功，将员工id存入session，返回成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理session中所保存当前员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     *新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        //设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

       /* employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //获取当前登录用户的id
        Long empId=(Long) request.getSession().getAttribute("employee");

        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/

        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页查询员工信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器，设置分页条件
        Page pageInfo=new Page(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<Employee>();
        //添加过滤条件,如果搜索框有值  isNotEmpty：不为空串也不为空，对于获取的数据，判断不为空即可
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);//第一个参数表示name不为空才会执行
        //添加排序条件,根据更新时间排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo,queryWrapper);//会自动给Page对象的属性都赋值,即pageInfo

        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息，无论是修改状态还是编辑操作
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        /*employee.setUpdateTime(LocalDateTime.now());//设置修改的时间
        employee.setUpdateUser((long)request.getSession().getAttribute("employee"));//设置执行修改的用户id*/
        employeeService.updateById(employee);
        return R.success("员工状态修改完毕");
    }

    /**
     * 根据id查询员工信息，用于回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }
}
